import FoodCart from '../../models/shop/FoodCart.js'
import com from './com.js'
let cart = new FoodCart()
export default {
	myProducts:[],
	cartIds:[],
	lastAddTime:0,
	init(cbFunc = ()=>{}){
		cart.setIgnore(['guide','info','items','tags','pics']).setMy().setGroup(['all']).getMany().then(res=>{
			this.lastAddTime = 0
			console.log(res)
			this.myProducts = res
			cbFunc(res)
			let cartIds = []
			for (let index in res) {
				cartIds.push(res[index].product.id)
			}
			this.cartIds = cartIds
		})
	},
	getListLocal(){
		return this.myProducts
	},
	getIds(){
		return this.cartIds
	},
	add(product,num){
		let item = this.getItem(product)
		if(!item){
			if(com.getTimestamp() - this.lastAddTime < 1){
				return false
			}
			this.lastAddTime = com.getTimestamp()
			this.myProducts.push({
				id:'',
				product:{id:product},
				num:1
			})
			cart.setProduct(product).setNum(num).create(res=>{
				this.init()
			})
		}else{
			com.showToast('已存在于购物车')
		}
	},
	delete(id){
		cart.delete(id,res=>{this.init()})
		this.cartIds = com.arrayDelValue(this.cartIds,id)
	},
	deleteAll(){
		this.myProducts.map(data,index=>{
			setTimeout(this.cart.delete(id,res=>{}),index*300)
		})
	},
	getItem(product){
		for (let index in this.myProducts) {
			if(this.myProducts[index].product.id == product){
				return this.myProducts[index].product.id
			}
		}
		return false
	},
}